package classpath

import (
	"path/filepath"
	"io/ioutil"
	"archive/zip"
	"errors"
)

/**
需要指定一个Zip文件地址
 */
type ZipEntry struct {
	absPath string
}

func newZipEntry(path string) *ZipEntry {
	absDir, err := filepath.Abs(path)
	if err != nil {
		panic(err) //
	}
	return &ZipEntry{absDir}
}

// 将zip文件解压开，逐个寻找名字是ClassName的
func (self *ZipEntry)readClass(className string) ([]byte, Entry, error) {
	reader, err := zip.OpenReader(self.absPath) //reader为zipReader
	if err != nil {
		return nil, nil, err
	}

	defer reader.Close() //指定操作完文件后关闭reader
	for _, f := range reader.File {
		// f是文件指针
		if f.Name == className {
			rc, err := f.Open()
			if err != nil {
				return nil, nil, err
			}
			defer rc.Close()
			data, err := ioutil.ReadAll(rc)
			if err != nil {
				return nil, nil, err
			}
			return data, self, err
		}

	}

	return nil, nil, errors.New("class not found: " + className)
}

func (self *ZipEntry)String() string {
	return self.absPath //返回目录
}
